package com.ctgu.springboot.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ctgu.springboot.common.QiniuUploadUtils;
import com.ctgu.springboot.common.QueryPageParam;
import com.ctgu.springboot.common.Result;
import com.ctgu.springboot.entity.PubResouse;
import com.ctgu.springboot.mapper.PubResouseMapper;
import com.ctgu.springboot.service.PubResouseService;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cs
 * @since 2023-07-07
 */
@RestController
@RequestMapping("/resource")
public class PubResouseController {

    @Value("${files.upload.path}")
    private String fileUploadPath;

    @Resource
    private PubResouseMapper pubResouseMapper;

    @Autowired
    private PubResouseService pubResouseService;

    /**
     * 文件上传
     * @param
     * @return
     * @throws IOException
     */
    //@PostMapping("/upload")
    //public String upload(@RequestParam MultipartFile file) throws IOException {
    //    String originalFilename = file.getOriginalFilename();
    //    String type = FileUtil.extName(originalFilename);
    //    long size = file.getSize();
    //
    //    // 定义一个文件唯一的标识码
    //    String fileUUID = IdUtil.fastSimpleUUID() + StrUtil.DOT + type;
    //
    //    File uploadFile = new File(fileUploadPath + fileUUID);
    //    // 判断配置的文件目录是否存在，若不存在则创建一个新的文件目录
    //    File parentFile = uploadFile.getParentFile();
    //    if(!parentFile.exists()) {
    //        parentFile.mkdirs();
    //    }
    //
    //    String url;
    //    InputStream is = file.getInputStream();
    //    // 获取文件的md5
    //    String md5 = SecureUtil.md5(is);
    //    // 从数据库查询是否存在相同的记录
    //    PubResouse dbFiles = getFileByMd5(md5);
    //    if (dbFiles != null) {
    //        url = dbFiles.getUrl();
    //    } else {
    //        // 上传文件到磁盘
    //        file.transferTo(uploadFile);
    //        // 数据库若不存在重复文件，则不删除刚才上传的文件
    //        url = "http://localhost:9090/resource/" + fileUUID;
    //    }
    //    is.close();
    //
    //    SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
    //    sdf.applyPattern("yyyy-MM-dd HH:mm:ss");// a为am/pm的标记
    //    Date date = new Date();// 获取当前时间
    //
    //    PubResouse saveFile = new PubResouse();
    //    saveFile.setPubName(originalFilename);
    //    saveFile.setPubType(type);
    //    saveFile.setPubSize(size/1024+"KB"); // 单位 kb
    //    saveFile.setUrl(url);
    //    saveFile.setMd5(md5);
    //    saveFile.setDownCount(0);
    //    saveFile.setPubTime(sdf.format(date));
    //    pubResouseMapper.insert(saveFile);
    //
    //    return url;
    //}
    //
    //private PubResouse getFileByMd5(String md5) {
    //    // 查询文件的md5是否存在
    //    QueryWrapper<PubResouse> queryWrapper = new QueryWrapper<>();
    //    queryWrapper.eq("md5", md5);
    //    List<PubResouse> filesList = pubResouseMapper.selectList(queryWrapper);
    //    return filesList.size() == 0 ? null : filesList.get(0);
    //}
    //
    ///**
    // * 文件下载
    // * @param fileUUID
    // * @param response
    // * @throws IOException
    // */
    //@GetMapping("/{fileUUID}")
    //public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
    //
    //    String url = "http://localhost:9090/resource/" + fileUUID;
    //    PubResouse pubResouse = pubResouseService.selectByUrl(url);
    //    pubResouse.setDownCount(pubResouse.getDownCount()+1);
    //    pubResouseService.updateById(pubResouse);
    //
    //    // 根据文件的唯一标识码获取文件
    //    File uploadFile = new File(fileUploadPath + fileUUID);
    //    // 设置输出流的格式
    //    ServletOutputStream os = response.getOutputStream();
    //    response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
    //    response.setContentType("application/octet-stream");
    //
    //    // 读取文件的字节流
    //    os.write(FileUtil.readBytes(uploadFile));
    //    os.flush();
    //    os.close();
    //}

    @PostMapping("upload")
    public Result upload(MultipartFile file){
        System.out.println("file = "+file);
        String Filename = file.getOriginalFilename();
        System.out.println("Filename = "+Filename);
        String type = FileUtil.extName(Filename);
        long size = file.getSize();
        SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
        sdf.applyPattern("yyyy-MM-dd HH:mm:ss");// a为am/pm的标记
        Date date = new Date();// 获取当前时间

        PubResouse saveFile = new PubResouse();
        saveFile.setPubName(Filename);
        saveFile.setPubType(type);
        saveFile.setPubSize(size/1024+"KB"); // 单位 kb
        saveFile.setUrl("http://150.158.87.29:9090/resource/"+(String) QiniuUploadUtils.upload(file).getData());
        saveFile.setDownCount(0);
        saveFile.setPubTime(sdf.format(date));
        pubResouseMapper.insert(saveFile);
        return QiniuUploadUtils.upload(file);
    }

    @GetMapping("/{fileUUID}")
    public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {

        String searchUrl = "http://150.158.87.29:9090/resource/" + fileUUID;
        String fileUrl = "http://rxs1e2bv8.hn-bkt.clouddn.com/"+fileUUID;
        PubResouse pubResouse = pubResouseService.selectByUrl(searchUrl);
        pubResouse.setDownCount(pubResouse.getDownCount()+1);
        pubResouseService.updateById(pubResouse);
        URL url = new URL(fileUrl);
        InputStream is = url.openStream();
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename="+URLEncoder.encode(fileUUID, "UTF-8"));
        IOUtils.copy(is, response.getOutputStream());
        response.flushBuffer();
    }



    //删除
    @GetMapping("/del")
    public Result getById(@RequestParam Integer pub_id) {
        return pubResouseService.removeById(pub_id)?Result.suc():Result.fail();
    }

    @RequestMapping("/list")
    public List<PubResouse> list(){
        return pubResouseService.list();
    }

    /**
     * 分页显示公共资源文件列表
     * @return
     */
    @PostMapping("/listPage")
    public Result listPage(@RequestBody QueryPageParam query){
        IPage<PubResouse> result = pubResouseService.listPage(query);
        return Result.suc(result.getRecords(), result.getTotal());
    }

    @GetMapping("/getUrl")
    public Result getUrl(@RequestParam Integer pub_id){
        return (pubResouseService.getById(pub_id).getUrl()!=null)? Result.suc(pubResouseService.getById(pub_id).getUrl()):Result.fail();
    }

}
